package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.iot08.api.config.properties.ListDataProperties;
import com.iot08.common.constant.ConstKafka;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.common.utils.CollectionUtil;
import com.iot08.common.utils.MessageUtils;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import com.iot08.api.vo.request.SetDeviceDataFlowReqVO;
import com.iot08.api.vo.request.base.BaseAccountReqVO;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.DeviceDataFlow;
import com.iot08.common.entity.app.DeviceMessage;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2020/12/15 11:00
 */
@Slf4j
@Service
public class DeviceDataFlowService extends BaseService<DeviceDataFlow> {

    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceMessageService deviceMessageService;
    @Resource
    private ListDataProperties listDataProperties;
    @Resource
    private KafkaService kafkaService;

    private long dataFlowQlimitTime = 3 * 60;

    /**
     * @param id
     * @time: 2020/12/16 15:14
     * @author: Rock
     * @version 1.0
     */
    public DeviceDataFlow getById(String id) {
        DeviceDataFlow dataFlow = this.findById(id);
        if (dataFlow == null) {
            //没有记录则添加
            dataFlow = new DeviceDataFlow();
            dataFlow.setId(id);
            dataFlow.setCreateTime(new Date());
            this.save(dataFlow);
        }
        return dataFlow;
    }

    /**
     * 获取流量设置数据
     *
     * @param imei
     * @param vo
     * @time: 2020/12/16 11:35
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getInfo(String imei, BaseAccountReqVO vo) {
        DeviceDataFlow dataFlow = getById(imei);
        //最近一次更新的时间  找不到给 -1
        Long updateTime = dataFlow.getUpdateTime() == null ? -1 : dataFlow.getUpdateTime();
        if (System.currentTimeMillis() / 1000 - updateTime > dataFlowQlimitTime
                && !Const.INT_1.equals(dataFlow.getStatus())) {
            //如果不是超额断网状态才下发
            //间隔大于30分钟,向设备下发一个查询流量的96指令 (这个指令并不 缓存redis)
//            JSONObject json = new JSONObject();
//            json.put("openid", vo.getOpenid());
//            kafkaService.emitDeviceDemand(imei, ConstKafka.DEVICE_TYPE_96, json);
            //更新查询时间
            this.updateById(imei, new Update().set("queryTime", System.currentTimeMillis() / 1000L));
        }
        int packageValue = dataFlow.getPackageValue() == null ? 0 : dataFlow.getPackageValue();
        List<Map<String, Object>> dataFlowList = new ArrayList<>(listDataProperties.getFlow());
        Map<String, Object> temp = new HashMap<>();
        temp.put("ident", 200);
        temp.put("title", "自定义");
        temp.put("value", packageValue);
        dataFlowList.add(temp);

        Double nowDataflow = dataFlow.getNowDataflow() == null ? 0 : dataFlow.getNowDataflow();
        Integer nowMonthPlanValue = packageValue;
        for (Map<String, Object> map : dataFlowList) {
            if (map.get("ident").equals(dataFlow.getMonthPlan())) {
                nowMonthPlanValue = (Integer) map.get("value");
            }
        }
        ResponseMap res = ResponseMap.success();
        res.put("updateTime", updateTime);
        res.put("endDay", dataFlow.getEndDay() == null ? 1 : dataFlow.getEndDay());
        res.put("nowDataflow", nowMonthPlanValue - nowDataflow == 0 ? 0 : nowMonthPlanValue - nowDataflow);
        res.put("useDataflow", nowDataflow == 0 ? 0 : nowDataflow);
        res.put("monthPlan", dataFlow.getMonthPlan() == null ? 100 : dataFlow.getMonthPlan());
        res.put("packageList", dataFlowList);
        return res;
    }

    /**
     * 设置流量设置数据
     *
     * @param imei
     * @param vo
     * @time: 2021/1/13 10:54
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap setDeviceDataFlow(String imei, SetDeviceDataFlowReqVO vo) {
        String openid = vo.getOpenid();
        DeviceDataFlow dataFlow = getById(imei);
        Device device = deviceService.findById(imei);
        if (device == null) {
            log.error("Device is null. imei={}", imei);
            return ResponseMap.fail(ResponseEnum.STATUS2001.getCode(), ResponseEnum.STATUS2001.getMsg(), imei);
        }
        if (StringUtil.isBlank(openid)) {
            openid = vo.getOpenid();
        }
        String deviceName = deviceService.getDeviceName(device);
        Object relationship = null;
        if (CollectionUtil.containsKey(device.getUserMap(), openid)) {
            relationship = device.getUserMap().get(openid).get("relationship");
        }
        dataFlow.setEndDay(vo.getEndDay() == null ? 1 : vo.getEndDay());
        dataFlow.setMonthPlan(vo.getPackageIdent() == null ? 100 : vo.getPackageIdent());
        dataFlow.setPackageValue(vo.getPackageValue() == null ? 0 : vo.getPackageValue());
        Update updateDataFlow = new Update();
        updateDataFlow.set("endDay", dataFlow.getEndDay());
        updateDataFlow.set("monthPlan", dataFlow.getMonthPlan());
        updateDataFlow.set("packageValue", dataFlow.getPackageValue());
        this.updateById(imei, updateDataFlow);

        Integer nowMonthPlanValue = dataFlow.getPackageValue() == null ? 0 : dataFlow.getPackageValue();
        String nowonthPlanTitle = "自定义";
        List<Map<String, Object>> dataFlowList = new ArrayList<>(listDataProperties.getFlow());
        for (Map<String, Object> map : dataFlowList) {
            if (map.get("ident").equals(dataFlow.getMonthPlan())) {
                nowMonthPlanValue = (Integer) map.get("value");
                nowonthPlanTitle = (String) map.get("title");
            }
        }
        if (new Integer(200).equals(dataFlow.getMonthPlan())) {
            nowonthPlanTitle = nowMonthPlanValue + "MB";
        }
        //发送kafka
//        JSONObject json = new JSONObject();
//        json.put("endDay", vo.getEndDay() == null ? 1 : vo.getEndDay());
//        json.put("monthPlanV", nowMonthPlanValue);
//        json.put("openid", vo.getOpenid());
//        kafkaService.emitDeviceDemand(imei, ConstKafka.DEVICE_TYPE_98, json);

        //拼接 显示的数据, APP推送或 显示时都可使用,
        String msg = MessageUtils.getLocale("API.pushTitle.setDataFlow", deviceName, relationship, nowonthPlanTitle);
//        String msg = String.format("【%s】的%s设置本月流量套餐为%s，超过后设备会自动断开网络", deviceName, relationship, nowonthPlanTitle);
        if (new Integer(100).equals(vo.getPackageIdent())) {
            //不限制
            msg = MessageUtils.getLocale("API.pushTitle.setDataFlowNotLimit", deviceName, relationship, nowonthPlanTitle);
        }
        DeviceMessage deviceMessage = new DeviceMessage();
        deviceMessage.setImei(imei);
        deviceMessage.setName(deviceName);
        deviceMessage.setType("setDataFlow");
        deviceMessage.setOperatorName(relationship == null ? null : relationship.toString());
        deviceMessage.setMonthPlanV(nowMonthPlanValue);
        deviceMessage.setMsgTitle(msg);
        deviceMessage.setMsgContent(msg);
        deviceMessageService.save(deviceMessage);

        if (CollectionUtil.isNotEmpty(device.getUserMap())) {
            //发送设置推送
            JSONObject pushData = new JSONObject();
            JSONObject message = new JSONObject();
            message.put("imei", imei);
            message.put("openid", openid);
            message.put("type", "setDataFlow");
            message.put("operatorName", relationship);
            message.put("monthPlanV", nowMonthPlanValue);
            message.put("msgTitle", msg);
            message.put("msgContent", msg);
            message.put("timestamp", DateUtil.nowTimestampToDouble());
            pushData.put("type", ConstKafka.ACCOUNT_MESSAGE);
            pushData.put("message", message);
            for (String tempOpenid : device.getUserMap().keySet()) {
                //除自己外的都发推送
                if (vo.getOpenid().equals(openid)) {
                    continue;
                }
                kafkaService.sendPushToAccount(ConstKafka.ACCOUNT_TYPE_3, openid, pushData);
            }
        }
        return ResponseMap.success();
    }
}
